package com.swdegao.iot.netty.server;

import com.swdegao.iot.netty.entity.Parameter;
import com.swdegao.iot.netty.server.channelhandler.HeartBeatClientHandler;
import com.swdegao.iot.netty.server.channelhandler.ParseMessgaeHandler;
import com.swdegao.iot.netty.server.channelhandler.PushMessgaeHandler;
import com.swdegao.iot.netty.server.channelhandler.SaveMessgaeHandler;
import com.swdegao.iot.netty.server.decoder.DG_DATADecoder;
import com.swdegao.iot.netty.server.guoxinhandler.GuoXinParseMessgaeHandler;
import com.swdegao.iot.netty.server.guoxinhandler.GuoXinPushMessgaeHandler;
import com.swdegao.iot.netty.server.guoxinhandler.GuoXinSaveMessgaeHandler;
import com.swdegao.iot.netty.utils.ByteUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class TestHandler extends ByteToMessageDecoder {
    /**
     * websocket定义请求行前缀
     */
    private static final String WEBSOCKET_LINE_PREFIX = "GET /ws";
    /**
     * websocket的uri
     */
    private static final String WEBSOCKET_PREFIX = "/ws";
    /**
     * 检查10个字节，没有空格就是自定义协议
     */
    private static final int SPACE_LENGTH = 12;


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

//        System.out.println("before :" + ctx.pipeline().toString());
//        if (isWebSocketUrl(in)) {
//            System.out.println("addWebSocketHandlers");
//
////            addWebSocketHandlers(ctx.pipeline());
//        } else if (isCustomProcotol(in)) {
//            System.out.println("addTCPProtocolHandlers");
//
////            addTCPProtocolHandlers(ctx.pipeline());
//        } else {
//            System.out.println("addHTTPHandlers");
////            addHTTPHandlers(ctx.pipeline());
//        }
//        ctx.pipeline().remove(this);
//        System.out.println("after :" + ctx.pipeline().toString());


        in.markReaderIndex();
        byte[] content = new byte[SPACE_LENGTH];
        in.readBytes(content);
        in.resetReaderIndex();
        String s = new String(content, CharsetUtil.UTF_8);
//        String clintdata= ByteBufUtil.hexDump(byteBuf).toUpperCase();
        String clintdata= ByteUtils.bytesToHexString(content);
        if(null !=clintdata ){
            //德高协议
            if(clintdata.substring(0, 2).equals("80")){
            ctx.pipeline().addLast(new IdleStateHandler(Parameter.heartbeat_cycle_check,0,0, TimeUnit.SECONDS));
            ctx.pipeline().addLast(new DG_DATADecoder(1<<20,2,2,-4,0));
            ctx.pipeline().addLast(new HeartBeatClientHandler());
            ctx.pipeline().addLast(new ParseMessgaeHandler());
            ctx.pipeline().addLast(new SaveMessgaeHandler());
            ctx.pipeline().addLast(new PushMessgaeHandler());
            } else if(clintdata.substring(0,4).equals("AA55")){
                //国信集中器
                ctx.pipeline().addLast(new IdleStateHandler(Parameter.heartbeat_cycle_check,0,0, TimeUnit.SECONDS));
                ctx.pipeline().addLast(new DG_DATADecoder(1<<20,2,2,-4,0));
                ctx.pipeline().addLast(new HeartBeatClientHandler());
                ctx.pipeline().addLast(new GuoXinParseMessgaeHandler());
                ctx.pipeline().addLast(new GuoXinSaveMessgaeHandler());
                ctx.pipeline().addLast(new GuoXinPushMessgaeHandler());
            }
        }
        //ctx.pipeline().remove(this);





    }

    /**
     * 是否有websocket请求行前缀
     *
     * @param byteBuf
     * @return
     */
    private boolean isWebSocketUrl(ByteBuf byteBuf) {
        if (byteBuf.readableBytes() < WEBSOCKET_LINE_PREFIX.length()) {
            return false;
        }
        byteBuf.markReaderIndex();
        byte[] content = new byte[WEBSOCKET_LINE_PREFIX.length()];
        byteBuf.readBytes(content);
        byteBuf.resetReaderIndex();
        String s = new String(content, CharsetUtil.UTF_8);
        return s.equals(WEBSOCKET_LINE_PREFIX);
    }

    /**
     * 是否是自定义是有协议
     * @param byteBuf
     * @return
     */
    private boolean isCustomProcotol(ByteBuf byteBuf) {
        byteBuf.markReaderIndex();
        byte[] content = new byte[SPACE_LENGTH];
        byteBuf.readBytes(content);
        byteBuf.resetReaderIndex();
        String s = new String(content, CharsetUtil.UTF_8);
        return s.indexOf(" ") == -1;
    }

    /**
     * 判断协议类型
     * @param byteBuf
     * @return
     */
    private boolean isDeGaoCustomProcotol(ByteBuf byteBuf) {
        byteBuf.markReaderIndex();
        byte[] content = new byte[SPACE_LENGTH];
        byteBuf.readBytes(content);
        byteBuf.resetReaderIndex();
        String s = new String(content, CharsetUtil.UTF_8);
//        String clintdata= ByteBufUtil.hexDump(byteBuf).toUpperCase();
        String clintdata2= ByteUtils.bytesToHexString(content);
        return s.indexOf(" ") == -1;
    }



    /**
     * 动态添加WebSocket处理器
     * @param pipeline
     */
//    private void addWebSocketHandlers(ChannelPipeline pipeline) {
//        pipeline.addLast(new HttpServerCodec());
//        pipeline.addLast(new HttpObjectAggregator(8192));
//        pipeline.addLast(new WebSocketServerProtocolHandler(WEBSOCKET_PREFIX));
//        pipeline.addLast(new MyTextWebSocketFrameHandler());
//    }
    /**
     * 动态添加TCP私有协议处理器
     * @param pipeline
     */
//    private void addTCPProtocolHandlers(ChannelPipeline pipeline) {
//        pipeline.addLast(new CustomDecoder(1024, 1, 4));//这里1代表长度属性是从索引1位置开始的，4代表有4个字节的长度
//        pipeline.addLast(new CutsomServerHandler());
//    }


    /**
     * 动态添加HTTP处理器
     * @param pipeline
     */
//    private void addHTTPHandlers(ChannelPipeline pipeline) {
//        pipeline.addLast(new HttpServerCodec());
//        pipeline.addLast(new HttpObjectAggregator(8192));
//        pipeline.addLast(new MyHttpServerHandler());
//
//
//    }

}
